package utils

import (
	"context"
	"crypto/tls"
	"mime/multipart"
	"net/http"
	"net/url"
	"time"

	"lab.com/conf"

	"github.com/tencentyun/cos-go-sdk-v5"
)

const (
	//DirTypeUserImage iota + 1
	DirTypeUserImage = iota + 1

	//DirTypeIURImage 2
	DirTypeIURImage

	//DirTypeCooperationImage 3
	DirTypeCooperationImage

	//DirTypeNewsImage 4
	DirTypeNewsImage

	//DirTypeAchievementImage 5
	DirTypeAchievementImage

	//DirTypePaper 6
	DirTypePaper

	//DirTypeForum 7
	DirTypeForum
)

// NewClient 创建cos 客户端 -- 存储桶名称，由bucketname-appid 组成，appid必须填入，可以在COS控制台查看存储桶名称。 https://console.cloud.tencent.com/cos5/bucket
// 替换为用户的 region，存储桶region可以在COS控制台“存储桶概览”查看 https://console.cloud.tencent.com/ ，关于地域的详情见 https://cloud.tencent.com/document/product/436/6224 。
func newClient() *cos.Client {
	u, _ := url.Parse(conf.CosConf.CosBucketURL)
	b := &cos.BaseURL{BucketURL: u}

	client := cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  conf.CosConf.CosSecretID,
			SecretKey: conf.CosConf.CosSecretKey,
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
			},
		},
		Timeout: 10 * time.Second,
	})

	return client
}

// UploadFileToCos 上传文件至cos
func UploadFileToCos(file multipart.File, fileName string, originDir string) (string, error) {
	client := newClient()

	key := originDir + "/" + fileName
	_, err := client.Object.Put(context.Background(), key, file, nil)
	if err != nil {
		return "", err
	}

	link := conf.CosConf.CosBucketURL + "/" + originDir + fileName

	return link, nil
}

// GetDirByType 根据类型获取文件夹名称
func GetDirByType(dirType int) string {
	switch dirType {
	case DirTypeUserImage:
		return "lab/user/image/"
	case DirTypeIURImage:
		return "lab/iur/image/"
	case DirTypeAchievementImage:
		return "lab/achievement/image/"
	case DirTypeNewsImage:
		return "lab/news/image/"
	case DirTypeCooperationImage:
		return "lab/cooperation/image/"
	case DirTypePaper:
		return "static/lab/paper/"
	case DirTypeForum:
		return "lab/forum/image/"
	default:
		return ""
	}
}
